/**
 * @developer：MR·Feng
 * 首页
 */

import styles from '@/styles/bill/bill.less';

import _ from 'lodash';
import moment from 'moment';
import { withRouter } from 'umi';
import React, { useEffect, useState } from 'react';
import { Table, Form, DatePicker, Button, Select } from 'antd';
import { layout } from '@/utils/datas';
import Request from '@/api/baseRequest';

import ExportJsonExcel from 'js-export-excel';

const { Option } = Select;

function Bill() {
    const [form] = Form.useForm();
    const [account, setaccount] = useState([]);
    const [billlist, setbilllist] = useState({});
    const [loading, setloading] = useState(false);
    const [pagination, setpagination] = useState({ current: 1, pageSize: 10 });

    // table显示格式
    const columns = [
        {
            title: '资源ID',
            dataIndex: 'resource_id',
            align: 'center',
            width: '20%',
        },
        {
            title: '类型',
            dataIndex: 'type',
            align: 'center',
            width: '10%',
        },
        {
            title: '实例名称',
            dataIndex: 'name',
            align: 'center',
            width: '10%',
        },
        {
            title: '成本',
            dataIndex: 'cost',
            align: 'center',
            width: '10%',
            render: (text) => <>&yen;{text}</>,
        },
        {
            title: '子公司',
            dataIndex: 'company_name',
            align: 'center',
            width: '10%',
        },
        {
            title: '比例',
            dataIndex: 'bili',
            align: 'center',
            width: '10%',
            render: (text) => `${text}%`,
        },
        {
            title: '分摊费用',
            dataIndex: 'company_cost',
            align: 'center',
            width: '10%',
            render: (text) => <>&yen;{text}</>,
        },
    ];

    // 页数改变
    const handleTableChange = (pagination) => setpagination(pagination);

    // AK账户名称选择
    const onChange = (value) => form.setFieldsValue({ id: value });

    // 获取子公司账单
    const getAllBill = async () => {
        let getbillform = _.cloneDeep(form.getFieldValue());
        getbillform.month = moment(getbillform.month).format('YYYY-MM');
        let { status, data } = await Request.postGetcombill(getbillform);
        if ([200, '200', 'OK'].includes(status)) {
            setbilllist({
                count: data.data.count,
                data: data.data.companybill || [],
            });
            setloading(false);
        }
    };

    const downloadFileToExcel = () => {
        let option = {}; //option代表的就是excel文件
        option.fileName = 'AK账户所有子公司分账'; //excel文件名称
        option.datas = [
            {
                sheetData: billlist.data, //excel文件中的数据源
                sheetName: '子公司分账', //excel文件中sheet页名称
                sheetFilter: columns.map((v) => v.dataIndex), //excel文件中需显示的列数据
                sheetHeader: columns.map((v) => v.title), //excel文件中每列的表头名称
            },
        ];
        let toExcel = new ExportJsonExcel(option); //生成excel文件
        toExcel.saveExcel(); //下载excel文件
    };

    // table footer
    const tableFooter = () => (
        <aside className={styles.tableFooter}>
            当月消费总额：&yen;{billlist.count}
        </aside>
    );

    // 副作用操作
    useEffect(async () => {
        setloading(true);
        let result = await Request.getAccount();
        setaccount(result.data);
        form.setFieldsValue({
            id: result.data[0].id,
            month: moment(),
        });
        getAllBill();

        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    return (
        <section className={styles.bill}>
            <Form
                {...layout}
                layout="inline"
                form={form}
                onFinish={() => getAllBill()}
                className={styles.billForm}
            >
                <Form.Item label="ak名称" name="id">
                    <Select
                        showSearch
                        style={{ width: 200 }}
                        placeholder="请选择AK账号"
                        onChange={onChange}
                    >
                        {(account || []).map((item) => (
                            <Option key={item.passwd} value={item.id}>
                                {item.name}
                            </Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="月份" name="month">
                    <DatePicker picker="month" />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        查询
                    </Button>
                    <Button type="primary" onClick={downloadFileToExcel}>
                        导出
                    </Button>
                </Form.Item>
            </Form>
            <Table
                columns={columns}
                rowKey={(record) => `${record.id}_${record.company_name}`}
                dataSource={billlist.data}
                pagination={pagination}
                loading={loading}
                footer={tableFooter}
                onChange={handleTableChange}
            />
        </section>
    );
}

export default withRouter(Bill);
